package com.flyou.ccnucenter.ui.frgment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;

import java.lang.reflect.Type;

/**
 * ============================================================
 * 项目名称：HenuCenterPro
 * 包名称：com.flyou.flying.ui.frgment
 * 文件名：BaseFragment
 * 类描述：
 * 创建人：flyou
 * 邮箱：fangjaylong@gmail.com
 * 创建时间：2015/9/23 10:36
 * 修改备注：
 * 版本：@version  V1.0
 * ============================================================
 */
public abstract class BaseFragment extends Fragment {
    public Activity context;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = onCreatView(inflater, container);
        initView();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        EventBus.getDefault().unregister(this);

        initData();
        super.onActivityCreated(savedInstanceState);
    }

    protected abstract View onCreatView(LayoutInflater inflater, ViewGroup container);

    protected abstract void initData();

    protected abstract void initView();

    @Override
    public void onAttach(Activity activity) {
        this.context = activity;
        super.onAttach(activity);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().register(this);
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName()); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
        MobclickAgent.onResume(context);          //统计时长
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName()); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(context);
    }

    /*
  * 对象转 json
  * obj 对象
  * */
    public String toJson(Object obj) {

        Gson gson = new Gson();
        return gson.toJson(obj);
    }

    /*
    * json转对象
    * classOfT 对象类型
    * */
    public <T> T toObj(String json, Type typeOfT) {
        Gson gson = new Gson();
        T t = gson.fromJson(json, typeOfT);
        return t;
    }
}
